<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX请求JSON</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
部门：<select name="dept" id='dept'>
    <!-- <option value="">请选择</option>  -->
</select>
名称：<input typye='text' id='key'/>
<button id="btngetJSON">getJSON获取员工</button>
<button id="btnAjax">Ajax获取员工</button>
<div id="content">
    <ul id='emp_list'>
    </ul>
</div>
<div id="app">
    <table id="emp">
        <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>性别</th>
            <th>科组</th>
            <th>身份证</th>
            <th>住址</th>
            <th>工资</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
</div>
</body>
</html>
<script>
    $(document).ready(function () {
        $.ajax({
            url: '/app/depts',
            type: 'GET',
            dataType: 'json',
            success: function (depts) {
                // $('#dept').empty();
                $.each(depts, function (i, item) {
                    $('#dept').append('<option value="' + item.id + '">' + item.name + '</option>');
                });
            }
        });

        $('#btngetJSON').click(function () {
            // get请求、返回JSON格式数据 $.getJSON(url,[data],[fn])
            $.getJSON('/app/emps/', {'key': $('#key').val(), 'dept_id': $('#dept').val()}, (resp) => {
                $('#emp_list').empty();
                $.each(resp, function (i, emp) {
                   // $('#emp_list').append("<li>" + emp.name + "</li>");
                    let tr = $('<tr>')
                            .append($('<td>').text(emp.id))
                            .append($('<td>').text(emp.name))
                            .append($('<td>').text(emp.gender))
                            .append($('<td>').text(emp.job))
                            .append($('<td>').text(emp.idcard))
                            .append($('<td>').text(emp.address))
                            .append($('<td>').text(emp.salary))
                    $('#emp>tbody').append(tr)
                });
            });
        });

        $('#btnAjax').click(function () {
            // console.log($('#dept').val());
            $.ajax({
                url: '/app/emps/',
                data: {'key': $('#key').val(), 'dept_id': $('#dept').val()},
                type: 'GET',
                dataType: 'json',
                success: function (resp) {
                    $('#emp_list').empty();
                    $.each(resp, function (i, emp) {
                        $('#emp_list').append("<li>" + emp.name + "</li>");
                    });
                },
            });
        });
    });
</script>